/**
 * 省市容器组件model
 * @author zhangxinyue(2019-12-18)
 */
import api from '../../api';

export default {
  namespace: 'addressM',
  state: {
    addressInfo: [], // 省市全量信息
    province: [], // 省份信息
  },
  effects: {
    //获取省市信息
    *getLocation({ payload }, { call, put, select }) {
      const addressInfo = yield select((state) => state.addressM.addressInfo);
      if (!addressInfo || addressInfo.length === 0) {
        const res = yield call(api.locations, {});
        if (res && res.code == 0) {
          let result = res.data;
          let province = [];
          // 抽取“省份”信息
          result.forEach((element) => {
            province.push({
              value: element.id,
              title: element.name,
            });
          });
          // 将省份信息存入state.province中
          yield put({
            type: 'updateData',
            payload: {
              addressInfo: result,
              province: province,
            },
          });
        }
      }
    },
  },
  reducers: {
    updateData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  subscriptions: {},
};
